package com.bookstore.bauhinia.user.controller;

import com.bookstore.bauhinia.pojo.User;
import com.bookstore.bauhinia.pojo.CommonResult;
import com.bookstore.bauhinia.user.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/user/insert")
    public CommonResult insertUser(@RequestBody User record){
        int result = userService.insert(record);
        System.out.println("*****插入结果:" + result);
        if (result > 0) {
            return new CommonResult(200, "插入数据库成功",record);
        } else {
            return new CommonResult(444,"插入数据库失败",null);
        }
    }
    @GetMapping("/user/get/{id}")
    public CommonResult getUserById(@PathVariable("id") int id){
        User user = userService.selectByPrimaryKey(id);
        System.out.println("*****查询结果:" + user);
        if (user != null) {
            return new CommonResult(200, "查询成功",user);
        } else {
            return new CommonResult(444,"没有对应记录,查询id:" + id,null);
        }
    }
    @GetMapping("/user/delete/{id}")
    public CommonResult deleteUserById(@PathVariable("id") int id){
        int result = userService.deleteByPrimaryKey(id);
        if (result > 0) {
            return new CommonResult(200, "删除数据成功");
        } else {
            return new CommonResult(444,"删除数据失败");
        }
    }
    @PostMapping("/user/update")
    public CommonResult updateUser(@RequestBody User record){
        int result = userService.updateByPrimaryKey(record);
        if (result > 0) {
            return new CommonResult(200, "更新数据成功",record);
        } else {
            return new CommonResult(444,"更新数据失败",null);
        }
    }

    @GetMapping("/user/all")
    public CommonResult getAllUsers(){
        List<User> users = userService.getAllUsers();
        if(users != null){
            return new CommonResult(200, "查询数据成功", users);
        } else {
            return new CommonResult(444, "查询数据失败", null);
        }
    }
}
